<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <!--        <a-collapse v-model="activeKey">-->
        <!--          <a-collapse-panel key="1" header="基本信息">-->
        <a-divider>基本信息</a-divider>
        <a-row :gutter="48">
          <a-col :span="8" :hidden="true">
            <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
              <a-input :max-length="255" :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入流程名称"></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
              <a-input v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
              <a-input v-model="model.createTime" placeholder="请输入申请时间" disabled ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
              <select-user-by-dep :multi="false" v-model="model.proposer" disabled></select-user-by-dep>
              <!-- :disabled=formDisabled -->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
              <j-select-depart v-model="model.proposerDeptId" disabled />
            </a-form-model-item>
          </a-col>
        </a-row>
        <!--          </a-collapse-panel>-->
        <a-divider>项目信息</a-divider>
        <!--          <a-collapse-panel key="2" header="项目信息">-->
        <a-row :gutter="48">
          <a-col :span="8">
            <a-form-model-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectId">
              <a-input
                v-if="formDisabled"
                readOnly
                @click.prevent="onDetail(model.projectId)"
                v-model="model.projectName"
                style="color: #1890FF; cursor: pointer;"
                placeholder="请选择项目名称"></a-input>
              <select-project-input
                v-else
                ref="projectInput"
                :disabled="formDisabled"
                v-model="model.projectId"
                :proDisabled="true"
                :allowClear="false"
                placeholder="请输入选择项目"
                :projectStatus="'2'"
                @input="projectChangeHandle" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="项目编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="projectNo">
              <a-input v-model="model.projectNo" :max-length="36" placeholder="请输入项目编号" disabled></a-input>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="合同名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="contractId">
              <a-input
                v-if="model.contractId"
                readOnly
                @click.prevent="goDetail(model.contractId)"
                v-model="model.contractName"
                style="color: #1890FF; cursor: pointer;"
                placeholder="请选择合同名称"></a-input>
              <select-contract-manager-input
                v-else
                :muitFlag="true"
                v-model="model.contractId"
                htlx="1"
                @back="contractIdBack"
                :allList="true"
                :triggerChange="true"
                :showName="'1'"
                disabled
              />
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">
              <select-user-by-dep :multi="false" v-model="model.undertaker" disabled></select-user-by-dep>
            </a-form-model-item>
          </a-col>

          <a-col :span="8">
            <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="managementTeam">
              <select-team-input
                v-model="model.managementTeam"
                :tdlx="1"
                disabled
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="生产团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="productionTeam">
              <a-input v-model="model.productionTeam" placeholder="请输入生产团队" disabled ></a-input>
              <a-input :hidden="true" v-model="model.productionTeamId" placeholder="请输入生产团队" disabled ></a-input>
              <!--                  <select-team-input-->
              <!--                    :disabled="formDisabled"-->
              <!--                    v-model="model.productionTeam"-->
              <!--                    :tdlx="1"-->
              <!--                    disabled-->
              <!--                  />-->
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业绩归属年度" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="year">
              <j-dict-select-tag type="list" v-model="model.year" dictCode="year" placeholder="请选择业绩归属年度" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="签订单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="signUnit">
              <select-Company-input v-model="model.signUnit" placeholder="请选择签订单位" disabled />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ownerUnit">
              <select-customer-input v-model="model.ownerUnit" placeholder="请选择业主单位" disabled/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="移交说明" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="instruction">
              <a-textarea :maxLength="500" :disabled="formDisabled" v-model="model.instruction" rows="4" placeholder="请输入移交说明"/>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-divider>移交信息</a-divider>
        <a-row :gutter="48">
          <a-table
            ref="table"
            size="middle"
            :scroll="{x:true}"
            :pagination="false"
            rowKey="id"
            :columns="itemColumns"
            :dataSource="itemDataSource">
            <!--                  class="j-table-force-nowrap">-->
            <!--                  <span slot="action" slot-scope="text, record">-->
            <!--                    <template v-if="!formDisabled">-->
            <!--                      <a @click="handleEdit4(record)">编辑</a>-->
            <!--                      <a-divider type="vertical"/>-->
            <!--                      <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete4(record.id)">-->
            <!--                        <a>删除</a>-->
            <!--                      </a-popconfirm>-->
            <!--                    </template>-->
            <!--                  </span>-->

          </a-table>
        </a-row>
        <a-divider>任务附件</a-divider>
        <a-row :gutter="48">
          <a-col :span="24">
            <a-form-model-item prop="taskFile">
              <j-upload :disabled="formDisabled" v-model="model.taskFile"></j-upload>
              <!-- <a-button v-else icon="download" @click="viewFile(model.attachments)">文件列表</a-button> -->
            </a-form-model-item>
          </a-col>
        </a-row>
        <!--          </a-collapse-panel>-->
        <!--          <a-collapse-panel key="2" header="移交信息">-->

        <!--          </a-collapse-panel>-->
        <!--        </a-collapse>-->

        <!--        <erp-audit-transfer-application-info-list ref="itemList"></erp-audit-transfer-application-info-list>-->
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <!-- 项目详情开始 -->
      <erp-project-report-modal ref="projectModalForm"></erp-project-report-modal>
      <!-- 项目详情结束 -->
      <erp-project-contract-manager-final-form ref="contractForm" ></erp-project-contract-manager-final-form>
    </j-form-container>

    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center; margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpAuditTransferApplicationFormPrint v-if="formBpm" class="print_style" id="auditTransferApplication" :formData="model" :formDataHistory="formData"></ErpAuditTransferApplicationFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction } from '@/api/manage'
  import { viewFile } from '@/utils/util'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import SelectProjectInput from '@/views/scy/components/SelectProjectInput'
  import SelectContractManagerInput from '@/views/scy/components/SelectContractManagerInput'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'

  import ViewFileModal from '@/views/scy/components/ViewFileModal';
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import ErpAuditTransferApplicationInfoList from '../ErpAuditTransferApplicationInfoList.vue';
  import ErpProjectContractReportForm from '../../../report/project/modules/ErpProjectContractReportForm.vue';
  import ErpProjectContractManagerFinalForm
    from '../../../report/project/modules/ErpProjectContractManagerFinalForm.vue';
  import ErpProjectReportModal from '@/views/erp/report/project/modules/ErpProjectReportModal'
  import Print from '@/utils/print/printarea.js';
  import ErpAuditTransferApplicationFormPrint from './ErpAuditTransferApplicationFormPrint' // 打印

  export default {
    name: 'ErpAuditTransferApplicationForm',
    mixins: [viewFile],
    components: {
      ErpProjectContractManagerFinalForm,
      ErpProjectContractReportForm,
      ErpAuditTransferApplicationInfoList,
      SelectUserByDep,
      SelectTeamInput,
      SelectCompanyInput,
      SelectCustomerInput,
      SelectProjectInput,
      SelectContractManagerInput,
      ViewFileModal,
      CommonFlowList,
      ErpProjectReportModal,
      ErpAuditTransferApplicationFormPrint
    },
    props: {
      // 流程表单data
      formData: {
        type: Object,
        default: () => {},
        required: false
      },
      // 表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    data () {
      return {
        model: {},
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          proposer: [
            { required: true, message: '请输入申请人!' }
          ],
          proposerDeptId: [
            { required: true, message: '请输入申请部门!' }
          ],
          // bpmBizTitle: [
          //   { required: true, message: '请输入流程标题!'},
          // ],
          createTime: [
            { required: true, message: '请输入申请日期!' }
          ],
          projectId: [
            { required: true, message: '请选择项目名称!' }
          ],
          instruction: [
            { required: true, message: '请输入移交说明!' }
          ]
        },
        url: {
          add: '/api/erp/audit/auditTransferApplication/erpAuditTransferApplication/add',
          edit: '/api/erp/audit/auditTransferApplication/erpAuditTransferApplication/edit',
          queryById: '/api/erp/audit/auditTransferApplication/erpAuditTransferApplication/queryById',
          getBillNo: '/api/erp/audit/auditTransferApplication/erpAuditTransferApplication/getBillNo',
          queryContractFinal: '/api/erp/omc/contractmanager/erpOmcContractManagerFinal/listForAudit',
          queryPaymentNode: '/api/erp/progress/erpProgressPaymentNode/queryListByContractId',
          queryInvoiceAmountCount: '/api/erp/finance/invoice/erpFinanceInvoiceApplicationBill/findInvoiceAmountCountByProjectAndPaymentNode',
          queryProjectTaskList: '/api/erp/omc/project/erpOmcProjectTask/list',
          queryInfoList: '/api/erp/audit/auditTransferApplication/erpAuditTransferApplicationInfo/list',
          queryProjectById: '/api/erp/project/report/erpProjectReport/queryById'
        },
        itemColumns: [
          {
            title: '序号',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1;
            }
          },
          // {
          //   title:'主表ID',
          //   align:"center",
          //   dataIndex: 'mainId',
          // },
          {
            title: '款项名称',
            align: 'center',
            dataIndex: 'paymentName'
          },
          {
            title: '应收款金额',
            align: 'center',
            dataIndex: 'receivableAmount'
          },
          {
            title: '已开票金额',
            align: 'center',
            dataIndex: 'invoicingAmount'
          },
          {
            title: '已回款金额',
            align: 'center',
            dataIndex: 'refundedAmount'
          }
        ],
        itemDataSource: [],
        dictOptions: {}
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 加载数据字典信息
      this.initDictConfig();
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
    },
    methods: {
      ...mapGetters(['userInfo']),

      async initDictConfig() {
        initDictOptions('erp_omc_team_manager,alias_name,id').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamId', res.result)
          }
        })
        initDictOptions('erp_omc_project,project_name,id').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'projectId', res.result)
          }
        })
      },
      // 获取编号
      getBillNo() {
        getAction(this.url.getBillNo, {}).then((res) => {
          if (res.success) {
            let data = res.result.records || res.result
            this.$set(this.model, 'billNo', data);
            // this.$set(this.model, 'bpmBizTitle', this.userInfo().employee.name+'-'+data);
          }
        })
      },
      goDetail(id) {
        this.$refs.contractForm.initData(id);
        this.$refs.contractForm.visible = true;
      },
      onDetail(id) {
        const that = this
        this.$nextTick(() => {
          getAction(this.url.queryProjectById, { id }).then((res) => {
            if (res.success) {
              const model = res.result
              that.$refs.projectModalForm.getDetail(model);
              that.$refs.projectModalForm.title = '项目一览表';
            }
          })
        })
      },

      add () {
        this.edit(this.modelDefault);
        this.getBillNo();
        this.model.proposer = this.userInfo().empId;
        this.model.proposerDeptId = this.userInfo().deptId;
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        // 子表置空
        this.itemDataSource = []
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);

        // 查询子表数据
        if (this.model.id) {
          getAction(this.url.queryInfoList, { mainId: this.model.id }).then((res) => {
            if (res.success) {
              this.itemDataSource = res.result.records || res.result
            }
          })
        }

        this.visible = true;
      },
      // 渲染流程表单数据
      showFlowData() {
        if (this.formBpm === true) {
          let params = { id: this.formData.dataId };
          getAction(this.url.queryById, params).then((res) => {
            if (res.success) {
              this.edit(res.result);
            }
          });
        }
      },

      // 项目选择回调
      async projectChangeHandle({ choseObj }) {
        let backItem = choseObj[0]
        // 切换项目 子表数据清空
        this.itemDataSource = []
        // 带出项目编号
        this.$set(this.model, 'projectNo', backItem.finalNo)

        // 带出项目真实名称
        this.$set(this.model, 'projectName', backItem.projectName)

        // 带出项目承接人
        this.$set(this.model, 'undertaker', backItem.undertaker)

        // 带出经营团队
        this.$set(this.model, 'managementTeam', backItem.teamName)

        // 查出项目档案子表的生产团队
        await getAction(this.url.queryProjectTaskList, { projectId: backItem.id }).then((res) => {
          if (res.success) {
            let { records } = res.result
            let teamTextTemp = []
            let teamIdTemp = []
            records.forEach(item => {
              teamIdTemp.push(item.productTeam);
              teamTextTemp.push(filterMultiDictText(this.dictOptions['teamId'], item.productTeam + ''))
            })
            let productTeamId = teamIdTemp.join(',')
            let productTeamText = teamTextTemp.join(',')
            // 塞入翻译过的团队名称并用逗号拼接
            console.log('翻译过的团队名为：', productTeamText)
            this.$set(this.model, 'productionTeam', productTeamText);
            this.$set(this.model, 'productionTeamId', productTeamId)
          }
        })

        // 带出业绩归属年度
        this.$set(this.model, 'year', backItem.year)

        // 带出签订单位
        this.$set(this.model, 'signUnit', backItem.signUnit)

        // 带出业主单位
        this.$set(this.model, 'ownerUnit', backItem.ownerUnit)

        // 查出合同 合同类型为1表示收款合同
        await getAction(this.url.queryContractFinal, { xmmc: backItem.id, htlx: 1 }).then((res) => {
          if (res.success) {
            if (res.result.records.length > 0) {
              // 查出收款合同
              this.$set(this.model, 'contractId', res.result.records[0].id)

              console.log('合同的数据', res.result.records[0])
              // 带出合同真实名称
              this.$set(this.model, 'contractName', res.result.records[0].htmc)

              var contractIdTemp = res.result.records[0].id
              // 查询收款进度中节点信息
              getAction(this.url.queryPaymentNode, { contractId: res.result.records[0].id }).then((res) => {
                if (res.success) {
                  if (res.result.length > 0) {
                    console.log('收款进度中节点信息为：', res.result)
                    res.result.forEach(item => {
                      this.itemDataSource.push({ paymentName: item.nodeName, receivableAmount: item.paymentMoney, refundedAmount: item.realCollectionPaymentMoney, invoicingAmount: item.invoicePaidAmount })
                      // //查询开票金额 废弃原因：迭代16.9开票申请单调整：5、开票申请单中子表中开票金额改为可输入为负数，主表中是否作废若选择是选择是之后，带出子表中相同的项目名称。过滤掉已关联的开票申请单的开票金额，则将子表中最新的开票金额（大于等于0）反写到项目的已开票金额。
                      // 所以不用再进行过滤废票
                      // getAction(this.url.queryInvoiceAmountCount, { projectContract: contractIdTemp,nodeId: item.id}).then((res) => {
                      //   if (res.success) {
                      //     //添加子表信息
                      //     this.itemDataSource.push({paymentName: item.nodeName,receivableAmount: item.paymentMoney,refundedAmount: item.realCollectionPaymentMoney,invoicingAmount: res.result ? res.result : 0})
                      //   }
                      // })
                    })
                  } else {
                    // 没有节点信息子表置空
                    this.itemDataSource = []
                  }
                }
              })
            } else {
              // 没有收款合同
              this.$set(this.model, 'contractId', null) // 合同id置空
              this.$set(this.model, 'contractName', null) // 合同名称置空
              this.itemDataSource = [] // 子表数据置空
            }
          }
        })

        console.log('项目带出的数据为：', backItem)
      },

      // 收款合同选择回调
      contractIdBack(item) {},

      // 清空项目关联的所有数据，包括项目id
      resetData() {
        this.$set(this.model, 'projectId', null)
        this.$set(this.model, 'projectNo', null)
        this.$set(this.model, 'projectName', null)

        // 带出业绩归属年度
        this.$set(this.model, 'year', null)

        // 带出签订单位
        this.$set(this.model, 'signUnit', null)

        // 带出业主单位
        this.$set(this.model, 'ownerUnit', null)

        this.$set(this.model, 'productionTeam', null);
        this.$set(this.model, 'productionTeamId', null)

        // 带出项目承接人
        this.$set(this.model, 'undertaker', null)

        // 带出经营团队
        this.$set(this.model, 'managementTeam', null)

        this.$set(this.model, 'contractId', null) // 合同id置空
        this.$set(this.model, 'contractName', null) // 合同名称置空
      },

      submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          if (!this.model.createTime || !this.model.proposer || !this.model.proposerDeptId) {
            this.$message.warning('请确保申请时间、申请人、申请部门字段值存在，如不存在请尝试刷新缓存！');
            this.$emit('unButtonDisable');
            return
          }

          // 有没有带出收款合同
          if (!this.model.projectId) {
            this.$message.warning('请选择项目名称!')
            this.$emit('unButtonDisable');
            return;
          }

          if (!this.model.contractId) {
            this.$message.warning('该项目还未签收款合同!')
            this.$emit('unButtonDisable');
            return;
          }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        var projectName = filterMultiDictText(this.dictOptions['projectId'], this.model.projectId + '')
        this.$set(this.model, 'bpmBizTitle', '移交申请-' + (this.model.projectId ? projectName + '-' : '') + this.userInfo().employee.name + '-' + moment(this.model.createTime).format('YYYY-MM-DD'));
        this.model.details = this.itemDataSource || []
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#auditTransferApplication',
          popTitle: '移交审计申请单详情 · 禾美环保',
          endCallback() {

          }
        })
      }
    }
  }
</script>
